package com.dyt.itool.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;


public class FileUtils {
	
	private static Logger logger = Logger.getLogger( FileUtils.class );
	
	public static byte[] readFile( File file ){
		try {
			FileInputStream fis = new FileInputStream( file );
			int length = fis.available();
			byte[] bytes = new byte[ length ];

			int readSize = 0;
			while( readSize < length ){
				readSize += fis.read( bytes, readSize, length - readSize );
			}
			fis.close();
			
			return bytes;
			
		} catch (FileNotFoundException e) {
			logger.error( "file not found" );
			logger.error( e.getStackTrace().toString() );
		} catch (IOException e) {
			logger.error( "readfile error" );
			logger.error( e.getStackTrace().toString() );
		}
		
		return null;
	}
	

	public static void writeFile(File file, byte[] bytes) {
		if( !file.getParentFile().exists() ){
			file.getParentFile().mkdirs();
		}
		
		try {
			
			FileOutputStream fos = new FileOutputStream( file );
			fos.write( bytes, 0 , bytes.length );
			fos.flush();
			fos.close();
			
		} catch (FileNotFoundException e) {
			logger.error( "file not found" );
			logger.error( e.getStackTrace().toString() );
		} catch (IOException e) {
			logger.error( "writefile error" );
			logger.error( e.getStackTrace().toString() );
		}
		
	}
	
	
	public static void copyFile( File srcFile, File destFile ){
		try{
			FileInputStream fis = new FileInputStream( srcFile );
			int size =  fis.available();
			byte[] fileBytes = new byte[size];
			fis.read(fileBytes, 0, size );
			fis.close();
			
			if( !destFile.getParentFile().exists( ) ){
				destFile.getParentFile().mkdirs( );
			}
			
			FileOutputStream fos = new FileOutputStream( destFile );
			fos.write( fileBytes, 0, size );
			fos.flush();
			fos.close( );
			
		}catch( Exception e ){
			e.printStackTrace();
		}
	}

	public static void copyDir( File srcDir, File destDir ){
		 File[] files = srcDir.listFiles( );
		for( File f : files ){
			if( f.isFile() ){
				copyFile( f, new File( destDir, f.getName() ) );
			}else{
				copyDir( f, new File( destDir, f.getName() ) );
			}
		}
	}

	public static void copyDirWithout( File srcDir, File destDir , String prefix ){
		File[] files = srcDir.listFiles( );
		for( File f : files ){
			if ( f.getName().startsWith( prefix ) ){
				continue;
			}

			if( f.isFile() ){
				copyFile( f, new File( destDir, f.getName() ) );
			}else{
				copyDirWithout( f, new File( destDir, f.getName() ), prefix );
			}
		}
	}

	public static void delete(String filePath) {
		File f = new File(filePath);

		if (f.exists()) {
			if (f.isFile()) {
				f.delete();
			}
		}

	}

}
